<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>图片懒加载</title>
  <style>
      body, html {
          width: 100%;
          height: 100%;
          margin: 0;
          padding: 0;
      }
      .img-list {
          width: 100%;
          height: 100%;
      }
      .img-list img {
          width: 100%;
      }
  </style>
</head>
<body>
  <div class="img-list">
    <!--  注意：需要在src中存一个默认的图片  -->
    <img id="msgId-1" data-src="./imgs/1.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-2" data-src="./imgs/2.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-3" data-src="./imgs/3.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-4" data-src="./imgs/4.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-5" data-src="./imgs/5.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-6" data-src="./imgs/6.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-7"  data-src="./imgs/7.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-8" data-src="./imgs/8.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-9" data-src="./imgs/9.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-10" data-src="./imgs/10.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-11" data-src="./imgs/11.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-12" data-src="./imgs/12.jpg" src="./imgs/1.jpg" alt="">
    <img id="msgId-13" data-src="./imgs/13.jpg" src="./imgs/1.jpg" alt="">
    <!--  如果没有data-src，下面获取的时候需要过滤掉，避免影响其他不需要懒加载的图片  -->
    <img src="" alt="">
  </div>
</body>
<script>
  function lazyImg() {
    // 获取可视区高度
    const viewHeight = document.body.offsetHeight
    // 获取带有data-src属性的所有img标签
    let imgList = document.querySelectorAll('img[data-src]')
    // 遍历所有的img，获取img距离适口上下左右的位置
    imgList.forEach(item => {
      // 用dataset获取自定义属性
      if (item.dataset.src === '') return
      // 用于获得页面中某个元素的左，上，右和下分别相对浏览器视窗的位置
      let rect = item.getBoundingClientRect()
      // 判断当前图片是否超过
      if (rect.bottom >= 0 && rect.top < viewHeight) {
        item.src = item.dataset.src
        item.removeAttribute('data-src')
      }
    })
  }

  window.addEventListener('scroll', lazyImg)
</script>
</html>
